package controllers;

import java.lang.reflect.Constructor;
import java.util.List;

import notifiers.Notifications;

import models.User;

import play.data.binding.Binder;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.i18n.Messages;
import play.mvc.Controller;

public class Users extends CRUD {
	public static void activateuser(String hash){
		List<User> users=User.findAll();
		User user=null;
	boolean sa7=false;
		for(User u: users){
		if(u.activationHash.equals(hash))
		user=u;
	}
	if(user!=null){
	user.isActivated=true;
	user.save();
	sa7=true;
	Notifications.welcome(user);
	}
	render(sa7,user);
	
	}
	 public static void create() throws Exception {
	        
		 ObjectType type = ObjectType.get(getControllerClass());
	        notFoundIfNull(type);
	        Constructor<?> constructor = type.entityClass.getDeclaredConstructor();
	        constructor.setAccessible(true);
	        Model object = (Model) constructor.newInstance();
	        Binder.bind(object, "object", params.all());
	        validation.valid(object);
	        if (validation.hasErrors()) {
	            renderArgs.put("error", Messages.get("crud.hasErrors"));
	            try {
	                render(request.controller.replace(".", "/") + "/blank.html", type, object);
	            } catch (TemplateNotFoundException e) {
	                render("CRUD/blank.html", type, object);
	            }
	        }
	        User user=(User)object;
	        String ur="localhost:9000/users/activateuser?hash="+user.activationHash;
	        if(user.email.endsWith("@student.guc.edu.eg")||user.email.endsWith("@guc.edu.eg")){
	        
	        	Notifications.activate(ur,user );
	        	user.save();
	        }else{
	        redirect(request.controller + ".blank");
	        }
	        
	        flash.success(Messages.get("crud.created", type.modelName));
	        if (params.get("_save") != null) {
	            redirect("/");
	        }
	        if (params.get("_saveAndAddAnother") != null) {
	            redirect(request.controller + ".blank");
	        }
	        redirect(request.controller + ".show", object._key());
	    }


}
